package group2assignone.ucm.customer;

import group2assignone.func.Authentication;
import group2assignone.dao.ClientComms;
import group2assignone.model.Customer;
import group2assignone.ucm.UCController;
import group2assignone.ucm.UCStartup;
import group2assignone.view.MainView;
import group2assignone.view.UITool;
import group2assignone.view.customer.CustomerWelcomeView;

/**
 * Use Case: Log in Customer
 * Pre-Condition: Customer inputs login details in the MainView UI 
 * and presses the "login" button (with 'general' selected)
 * Post-Condition: UI is updated  
 * 1. System gets login details from view
 * 2. System authenticates login details
 * 3. System logs Customer in and updates UI
 * 2a.  - Customer provides invalid login details
 *      - System displays error message and prompts user to reenter or cancel
 * 3a.  - System cannot log user in (connection error, already logged in)
 *      - System displays error message
 * @author group2
 */
public class UCLoginCustomer implements UCController {

    private Customer customer;
    private MainView view;
    private Authentication auth;
    private boolean ok,  ok2;
    private ClientComms client;

    /**
     * sets the view, initialise objects, gets the clientcommunication instance
     * @param view
     */
    public UCLoginCustomer(MainView view) {
        this.view = view;
        customer = new Customer();
        auth = new Authentication();
        client = UCStartup.getInstance().getClientComms();
    }

    public UCLoginCustomer() {
    }

    /**
     * method to log in the customer
     */
    public void run() {
        //1. System gets login details from view
        view.upload(customer);
        //2. System authenticates login details
        ok = auth.authCustomer(customer);
        if (ok) {
            //3. System logs in the Customer
            ok2 = client.login(customer);
            if (ok2) {
                //4. System updates the view
                CustomerWelcomeView gui = new CustomerWelcomeView(customer);
                gui.go();
                view.dispose();
            } else {    //3a.  - System cannot log user in 
                //(connection error, already logged in)
                //System displays error message
                UITool.displayError(client.getErrorMsg(), view);
            }
        } else {    //2a.  - Customer provides invalid login details
            //System displays error message
            UITool.displayError(auth.getErrorMsg(), view);
        }
    }
}
    

